const crypto=require('crypto');
const events=require('events');
const router=require('koa-router')();
const request=require('request-promise');
const {User,Auth}=require('../models/index');
const checkNotLogin=require('../middlewares/checkNotLogin');
const config=require('../config/config');

router.get('/github',checkNotLogin(),async ctx=>{
    ctx.redirect(config.auth.baseUri+`?client_id=${config.auth.client_id}&response_type=${config.auth.response_type}&scope=${config.auth.scope}&callback=${config.auth.callback}`);
});

router.get('/callback',checkNotLogin(),async ctx=>{
    let {code}=ctx.query,ee=new events();
    ee.on('fail',msg=>{
        ctx.flash={error:msg};
        ctx.redirect('/');
    });
    ee.on('success',user=>{
        ctx.session.loginUser={
            _id:user._id,
            githubId:user.githubId,
            name:user.name,
            email:user.email,
            avatar:user.avatar,
            score:user.score,
            intro:user.intro
        };
        return ctx.redirect('/');
    });
    let tokenRes=await request({
        uri:`${config.auth.baseUri}/token`,
        qs:{        
            code,
            client_id:config.auth.client_id,
            grant_type:'authorization_code',
            scope:config.auth.scope,
            callback:config.auth.callback
        },
        json:true
    });
    if(tokenRes.error)return ee.emit('fail',tokenRes.error);
    
    let access_token=tokenRes.access_token;
    //获取用户信息
    let userRes=await request({
        uri:'http://localhost:3900/api/v1/user/profile',
        qs:{
            access_token
        },
        json:true
    });

    if(200!=userRes.code)return  ee.emit('fail',userRes.error);

    let {data:authUser}=userRes;
    let user=await User.findOne({name:authUser.name,email:authUser.email});

    if(user){//已经注册过
        await Auth.update({user:user._id},{
            code,
            access_token,
            refresh_token:tokenRes.refresh_token,
            expires_in:tokenRes.expires_in,
            time:new Date()
        });   
    }else{//创建用户
        user=new User({
            githubId:authUser._id,
            name:authUser.name,
            password:'',
            email:authUser.email,
            avatar:authUser.avatar,
            regTime:new Date(),
            token:crypto.createHash('md5').update([config.secret,authUser.name,authUser.email].join('&')).digest('hex')
        });

        await Promise.all([
            user.save(),
            new Auth({
                code,
                access_token,
                refresh_token:tokenRes.refresh_token,
                expires_in:tokenRes.expires_in,
                time:new Date(),
                user:user._id
            }).save()
        ]);
    }
    ee.emit('success',user);
});

module.exports=router;